package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Notice;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.qo.NoticeQueryObject;
import cn.wolfcode.service.INoticeService;
import cn.wolfcode.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/notice")
public class NoticeController {
    @Autowired
    private INoticeService noticeService;


    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") NoticeQueryObject qo) {
        model.addAttribute("pageInfo", noticeService.query(qo));
        // 通过判断管理员权限来隐藏按钮
        model.addAttribute("isAdmin", UserContext.getEmployee().isAdmin());
        return "notice/list";
    }

    @RequestMapping("/delete")
    public String delete(Long id) {
        if (id != null) {
            noticeService.delete(id);
        }
        return "redirect:/notice/list";
    }

    // 查看
    @RequestMapping("/show")
    public String show(Long id,Model model) {
        if (id != null) {
            Long eId = UserContext.getEmployee().getId();
            System.out.println(eId);
            noticeService.updateRead(id,eId);
            model.addAttribute("notice", noticeService.get(id));
        }
        return "notice/show";
    }

    // 发布
    @RequestMapping("/push")
    public String push(Long id) {
        if (id != null) {
            noticeService.updateIssue(id);
        }
        return "redirect:/notice/list";
    }
    // 取消
    @RequestMapping("/remove")
    public String remove(Long id) {
        if (id != null) {
            noticeService.updateRemove(id);
        }
        return "redirect:/notice/list";
    }

    /*@RequestMapping("/saveOrUpdate")
    @RequirePermission(name = "公告编辑",expression = "notice:saveOrUpdate")
    public String saveOrUpdate(Notice notice) {
        if (notice.getId() != null) {
            noticeService.update(notice);
        } else {
            noticeService.insert(notice);
        }
        return "redirect:/notice/list";
    }*/

    // 异步提交表单方式
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Notice notice) {
        if (notice.getId() != null) {
            noticeService.update(notice);
        } else {
            Long id = noticeService.insert(notice);
            noticeService.insertRelation(id);
        }
        return new JsonResult(true,"添加成功");
    }
}
